<?php
	// Check crossing acess
	if (!defined('RIGHT_ACCESS') || !defined('ROOT_FOLDER'))
	{
		header('Content-Type: text/xml; charset=utf-8');
		echo '<?xml version="1.0"?>';
		echo '<atomtask>';
		echo '<request>error.request.invalid</request>';
		echo '</atomtask>';
		return;
	}	
	class User
	{
		public $user_id;
		public $username;
		public $password;
		public $email;

		public function create()
		{
			$query_string = 'INSERT INTO `user`(`username`, `email`) VALUES("'.$this->username.'","'.$this->email.'")';
			$result = DB::query($query_string);	
			if (!$result)
				return false;
			$hash = User::encode_password(mysql_insert_id(), $this->password);
			//echo mysql_insert_id().' '.$this->password.' '.$hash;
			$query_string = 'UPDATE `user` SET `password`="'.$hash.'" WHERE `username`="'.$this->username.'"';
			$result = DB::query($query_string);
			if (!$result)
				return false;
			return true;
		}
		public function check_exist()
		{
			$exist_count = 0;
			$result = DB::query('SELECT `username`, `email` FROM `user` WHERE `username`="'.$this->username.'" OR `email`="'.$this->email.'"');
			if ($result && mysql_num_rows($result) > 0)
			{
				if (mysql_num_rows($result) == 1)
				{
					$item = mysql_fetch_assoc($result);
					if ($item['username'] == $this->username)
						$exist_count = 1;
					if ($item['email'] == $this->email)
					{
						if ($exist_count == 1)
							$exist_count = 3;
						else
							$exist_count = 2;
					}
				}
				else
					$exist_count = 3;
			}
			return $exist_count;
		}
		public function get_information($username)
		{
			$result = DB::query('SELECT `user_id`, `password`, `email` FROM `user` WHERE `username`="'.$username.'"');
			if (!$result || mysql_num_rows($result) == 0)
				return false;
			$item = mysql_fetch_assoc($result);
			$this->user_id = $item['user_id'];
			$this->username = $username;
			$this->password = $item['password'];
			$this->email = $item['email'];
			return true;
		}
		public function update_information()
		{

		}
		public static function is_valid_username($username)
		{
			$pattern = '/^[a-zA-Z0-9_\.]{4,50}$/';
			return preg_match($pattern, $username);
		}

		public static function is_valid_password($password)
		{
			$pattern = '/^[a-zA-Z0-9]+$/';
			return preg_match($pattern, $password);
		}

		public static function is_valid_email($email)
		{
			$pattern = '/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';
			return preg_match($pattern, $email);
		}

		public static function encode_password($id, $unit_encode)
		{
			return md5(md5($id).$unit_encode);
		}
	}
?>